
package com.zy.ems.common.util;

import com.zy.ems.common.cache.CacheUtils;
import com.zy.ems.common.enums.CacheNameEnum;
import com.zy.ems.common.error.SysCode;
import com.zy.ems.common.exception.ApiException;
import com.zy.ems.utils.enums.UserTypeEnum;

/**
 * ClassName:TokenUtils <br/>
 * 
 * @author WangFei
 * @version
 * @see
 */
public class TokenUtils {

    private static final String TOKEN_SALT = "zy.com";

    private static final String TOKEN_USER_KEY = "zy-ems-user";

    private static final String TOKEN_MEMBER_KEY = "zy-ems-member";

    /**
     * 生成token <br/>
     *
     * @param userId 用户ID
     * @param mobile 手机号
     * @return
     */
    public static String getToken(String userId, String mobile,
            UserTypeEnum type) {
        if (StringUtils.isEmpty(userId, mobile)) {
            throw new ApiException(SysCode.sys_22);
        }

        if (type == null) {
            throw new ApiException(SysCode.sys_22);
        }

        long timeStamp = System.currentTimeMillis() / 1000;
        String str = userId + TOKEN_SALT + mobile + timeStamp;
        String token = Md5Util.getMd5Hex(str);

        // 保存KEY到缓存
        saveToken(userId, mobile, token, getKeyType(type));

        return token;
    }

    /**
     * 保存TOKEN到内存
     *
     * @param userId
     * @param mobile
     * @param token
     * @author WangFei
     */
    private static void saveToken(String userId, String mobile, String token,
            String typeKey) {
        if (StringUtils.isEmpty(typeKey)) {
            throw new ApiException(SysCode.sys_22);
        }

        String key = typeKey + userId;
        // 保存TOKEN默认30分钟
        CacheUtils.getInstance().hset(key, token, CacheNameEnum.TOKEN, 30 * 60);
    }

    /**
     * 检测token <br/>
     *
     * @param userId
     * @param mobile
     * @return
     * @author WangFei
     */
    public static boolean checkToken(String userId, String mobile,
            String accessToken, UserTypeEnum type) {

        String keyType = getKeyType(type);
        if (StringUtils.isEmpty(userId, mobile, accessToken, keyType)) {
            return false;
        }
        String key = keyType + userId;
        String token = CacheUtils.getInstance().hget(key, CacheNameEnum.TOKEN);

        if (StringUtils.isEmpty(token)) {
            return false;
        }

        return true;
    }

    /**
     * 获取键类型
     * 
     * @param type
     * @return
     */
    private static String getKeyType(UserTypeEnum type) {
        String typeKey = "";
        if (type == UserTypeEnum.USER) {
            typeKey = TOKEN_USER_KEY;
        }
        else if (type == UserTypeEnum.MEMBER) {
            typeKey = TOKEN_MEMBER_KEY;
        }

        return typeKey;
    }

}
